// vim: set et sw=4 ts=4 sts=4 fdm=marker ff=unix fenc=utf8 nobomb:
/**
 * Hepler function & objects
 *
 * @author mingcheng<i.feelinglucky#gmail.com>
 * @date   2009-11-15
 * @link   http://www.gracecode.com/
 */

~function() {
    var Util = YAHOO.util, Dom = Util.Dom, Event = Util.Event, Lang = YAHOO.lang;

    // 避免在没有本地存储的情况下出错
    /*
    if (Lang.isUndefined(localStorage)) {
        var localStorage = (function() {
            var data = {};
            return {
                setItem: function(name, value) {
                    data.name = value + '';
                },

                getItem: function() {
                    return data.name;
                }
            }
        })();
    }
    // */

    /**
     * 使用 localStorage 作为 logger
     */
    // /*
    var Logger = (function () {
        if (Lang.isUndefined(localStorage)) {
            return window.console;
        }
        var storage_falg = 'console_data';
        var handle = {
            log: function(message) {
                return $insert(message, 'log');
            },
            warn: function(message) {
                return $insert(message, 'warn');
            },
            info: function(message) {
                return $insert(message, 'info');
            },
            error: function(message) {
                return $insert(message, 'error');
            },
            clear: function() {
                localStorage.setItem(storage_falg, '[]');
            },
            getAll: function() {
                try {
                    return JSON.parse(localStorage.getItem(storage_falg)) || [];
                } catch (e) {
                    console.warn('logger: initial logger');
                    this.clear();
                    return [];
                }
            }
        };

        var consoleData = handle.getAll();
        var $insert = function (message, type) {
            message = (new Date().toString()) + ":\n  " + message + '';
            consoleData.push({
                message: message, type: type
            });

            //console.info(JSON.stringify(consoleData));
            return localStorage.setItem(storage_falg, JSON.stringify(consoleData));
        }

        return handle;
    })(); // logger


    var Func = {
        // 返回相对时间
        relativeTime: function(inputTimestampStr) {
            //console.info(inputTimestampStr);
            var inputTimestamp = Date.parse(inputTimestampStr);
            //console.info(inputTimestamp);
            var nowTimestamp = new Date().getTime();
            //console.info(nowTimestamp);

            var diff = (nowTimestamp - inputTimestamp) / 1000;
            if(diff < 15) {
                var between = "Just now";
            } else if(diff < 60) {
                var between = "Less than 1 minute ago";
            } else if(diff < 60 * 60) {
                var minutes = parseInt(diff / 60);
                var between = minutes + " minute" + ((minutes > 1) ? "s" : "") + " ago";
            } else if(diff < 60 * 60 * 24) {
                var hours = parseInt(diff / (60 * 60));
                var between = "about " + hours + " hour" + ((hours > 1) ? "s" : "") + " ago";
            } else if(diff < 60 * 60 * 24 * 30) {
                var days = parseInt(diff / (60 * 60 * 24));
                var between = "about " + days + " day" + ((days > 1) ? "s" : "") + " ago";
            } else if(diff < 60 * 60 * 24 * 30 * 12) {
                var months = parseInt(diff / (60 * 60 * 24 * 30));
                var between = "about " + months + " month" + ((months > 1) ? "s" : "") + " ago";
            } else {
                var between = "years ago";
            }

            //console.info(between);
            return between;
        },

        /**
         * 格式化字符串 from tbra
         * eg:
         * 	TB.common.formatMessage('{0}天有{1}个小时', [1, 24]) 
         *  or
         *  TB.common.formatMessage('{day}天有{hour}个小时', {day:1, hour:24}}
         * @param {Object} msg
         * @param {Object} values
         */
        formatMessage: function(msg, values, filter) {
            var pattern = /\{([\w-]+)?\}/g;
            return function(msg, values, filter) {
                return msg.replace(pattern, function(match, key) {
                    return Lang.isFunction(filter) ? filter(values[key], key) : values[key];
                });	
            }
        }(),

        // 设置标签数字
        setBadgeText: function(text)  {
            if (Lang.isObject(chrome)) {
                chrome.browserAction.setBadgeText({text: text + ''});
            }
        }
    } // func

    /**
     * 保存&获取配置
     */
    var Conf = {
        Get: function(opt_name, def) {
            var val = localStorage.getItem('conf_' + opt_name);
            return Lang.isNull(val) ? def + '' : val + '';
        },

        Set: function(opt_name, val) {
            return localStorage.setItem('conf_' + opt_name, val);
        }
    } // conf

    /**
     * 保存&获取状态信息
     */
    var Status = {
        Get: function(opt_name, def) {
            var val = localStorage.getItem('status_' + opt_name);
            return Lang.isNull(val) ? def + '' : val + '';
        },

        Set: function(opt_name, val) {
            return localStorage.setItem('status_' + opt_name, val);
        }
    } // status

    // auto expande URL with untr.im
    var AutoExpandURL = (function() {
        var API = 'http://untr.im/api/ajax/api', params = "submit=Lookup&url=";
        return function(url, callback) {
            YAHOO.util.Connect.asyncRequest("POST", API, {
                success: function (o) {
                    var div = document.createElement("DIV");
                    div.innerHTML = o.responseText;
                    var a = div.getElementsByTagName("A");
                    if (a.length === 2) {
                        callback.onSuccess(a[1].href);
                    } else {
                        callback.onError();
                    }
                },
                failure: callback.onError || function() {},
                timeout: config.timeout || 2000,
                cache: false
            }, params + encodeURIComponent(url), config.username);
        };
    })();

    // 暴露全局接口
    window.Helper = {
        Conf: Conf, Func: Func, Logger: Logger, Status: Status, AutoExpandURL: AutoExpandURL
    }
}();
